<template>
  <el-row>
    <el-col :span="24">
      <el-table :data="tableData" stripe style="width: 100%"  @selection-change="handleSelectionChange" ref="cartTable">
        <el-table-column type="selection" width="55" />
        <el-table-column label="图片" width="180">
          <template #default="scope">
            <img :src="reportImg(scope.row.images)" alt="" width="50%">
          </template>
        </el-table-column>
<!--        <el-table-column prop="id" label="编号" width="180" />-->
        <el-table-column prop="name" label="名称" width="180" />
        <el-table-column prop="discount" label="折扣" width="180" />
        <el-table-column prop="price" label="价格" width="180" />
        <el-table-column prop="count" label="数量" width="180">
          <template #default="scope">
            <el-input-number v-model="scope.row.count" :min="1"  @change="handleChange" />
          </template>
        </el-table-column>
      </el-table>
    </el-col>
    <el-col :span="12" :offset="12">
      <el-button type="primary" round @click="addOrder">下单</el-button>
    </el-col>
  </el-row>
</template>
<script setup>
import {findAll,addOrder as addOrderApi} from "../api/food.js";
import {ref,onMounted,getCurrentInstance} from "vue";
import {ElMessage} from "element-plus";

let {proxy} = getCurrentInstance()  // 从当前实例中获取 vue的代理
const tableData = ref([
  {
    "id": 1,
    "name": "麻辣小龙虾",
    "discount": 5.4,
    "price": 20,
    "images": "food/1.png"
  },
])
const orderItem = ref([])
function handleChange(){
  handleSelectionChange()
}

function handleSelectionChange(){
  orderItem.value = []
  let selectRow = proxy.$refs.cartTable.getSelectionRows()
  // console.log(selectRow)
  selectRow.forEach(item=>{
    orderItem.value.push({foodId:item.id,count:item.count})
  })
  // console.log(orderItem.value)
}

async function findFood(){
  let {data:data} = await findAll()
  console.log(data)
  tableData.value = data.data
  tableData.value.forEach(item=>{
    item.count = 0
  })
}
async function addOrder(){
  if(orderItem.value.length === 0){
    ElMessage.warning("请勾选要购买的商品")
    return;
  }
  // 向后台提交数据
  console.log(orderItem.value)
  let {data:data} = await addOrderApi(orderItem.value);
  // console.log(data)
  proxy.$router.push({path:'/pay',query:{orderId:data.data}})
}
onMounted(()=>{
  findFood()
})
</script>


<style scoped>

</style>